package cn.zhiquxing;

import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.Test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

public class LockSupportDemo {

    public static class ChangeObjectThread extends Thread {
        public ChangeObjectThread(@NotNull String name) {
            super(name);
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "即将进入无限时阻塞");
            LockSupport.park();
            if (Thread.currentThread().isInterrupted()) {
                System.out.println(Thread.currentThread().getName() + "被中断了，但仍会继续执行");
            } else {
                System.out.println(Thread.currentThread().getName() + "被重新唤醒了");
            }
        }
    }

    @Test
    public void testLockSupport() throws InterruptedException {
        ChangeObjectThread changeObjectThread1 = new ChangeObjectThread("线程一");
        ChangeObjectThread changeObjectThread2 = new ChangeObjectThread("线程二");
        changeObjectThread1.start();
        TimeUnit.SECONDS.sleep(1);
        changeObjectThread2.start();
        TimeUnit.SECONDS.sleep(1);
        changeObjectThread1.interrupt();
        LockSupport.unpark(changeObjectThread2);
    }

    @Test
    public void testLockSupport2() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            try {
                Thread.sleep(1000);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("即将进入无限时等待");
            LockSupport.park();
            System.out.println("被重新唤醒了");
        }, "演示线程");
        t1.start();
        LockSupport.unpark(t1);
        LockSupport.unpark(t1);
        Thread.sleep(2000);
        LockSupport.unpark(t1);
    }
}
